# encoding=utf-8
"""
响应校验中间件
"""
from scrapy.exceptions import IgnoreRequest
from scrapy.http import HtmlResponse
from zc_core.util.http_util import retry_request
from scrapy.utils.project import get_project_settings


class BaseValidateMiddleware(object):
    """
    基础业务校验中间件
    """
    def __init__(self):
        settings = get_project_settings()
        # 最大失败重试次数
        self.max_retry_times = settings.getint('RETRY_TIMES', 2)
        # 是否开启允许空响应体
        self.allow_empty_response = settings.getbool('ALLOW_EMPTY_RESPONSE', False)

    def process_request(self, request, spider):
        pass

    def process_response(self, request, response, spider):
        return self.validate(request, response, spider)

    def process_exception(self, request, exception, spider):
        _ = request
        _ = exception
        if not isinstance(exception, IgnoreRequest):
            spider.logger.error('validating error: {}'.format(exception))

    def validate(self, request, response, spider):
        """
        业务校验逻辑入口
        1、响应对象业务正常，返回response继续处理
        2、响应对象业务异常，返回request重新调度下载
        """
        meta = request.meta
        if meta:
            # 基础校验
            result = self.common_validate(request, response, spider)
            if result:
                return result

            # 业务校验
            if 'reqType' in meta:
                type = meta.get('reqType')
                if 'sku' == type:
                    return self.validate_sku(request, response, spider)
                elif 'spu' == type:
                    return self.validate_spu(request, response, spider)
                elif 'item' == type:
                    return self.validate_item(request, response, spider)
                elif 'price' == type:
                    return self.validate_price(request, response, spider)
                elif 'group' == type:
                    return self.validate_group(request, response, spider)
                elif 'order' == type:
                    return self.validate_order(request, response, spider)
                elif 'order_page' == type:
                    return self.validate_order_page(request, response, spider)
                elif 'catalog' == type:
                    return self.validate_catalog(request, response, spider)
                elif 'supplier' == type:
                    return self.validate_supplier(request, response, spider)
                elif 'brand' == type:
                    return self.validate_brand(request, response, spider)
                elif 'price' == type:
                    return self.validate_price(request, response, spider)
                elif 'stock' == type:
                    return self.validate_stock(request, response, spider)
                elif 'cert' == type:
                    return self.validate_cert(request, response, spider)
                elif 'pool' == type:
                    return self.validate_pool(request, response, spider)
                else:
                    return self.more_validation(request, response, spider)

        return response

    def common_validate(self, request, response, spider):
        """
        基础校验
        :param request:
        :param response:
        :param spider:
        :return:
        """
        meta = request.meta
        if meta:
            # 1、无响应重试
            if not response:
                spider.logger.error('no response...')
                return retry_request(request)
            # 2、响应无内容重试
            if not self.allow_empty_response and (isinstance(response, HtmlResponse) and not response.text and not response.body):
                spider.logger.info('[base]响应无内容：[%s]' % request.meta.get('validate_retry_times', 0))
                return retry_request(request)

    def validate_catalog(self, request, response, spider):
        return response

    def validate_supplier(self, request, response, spider):
        return response

    def validate_brand(self, request, response, spider):
        return response

    def validate_group(self, request, response, spider):
        return response

    def validate_sku(self, request, response, spider):
        return response

    def validate_spu(self, request, response, spider):
        return response

    def validate_item(self, request, response, spider):
        return response

    def validate_price(self, request, response, spider):
        return response

    def validate_order(self, request, response, spider):
        return response

    def validate_order_page(self, request, response, spider):
        return response

    def validate_stock(self, request, response, spider):
        return response

    def validate_cert(self, request, response, spider):
        return response

    def validate_pool(self, request, response, spider):
        return response

    def more_validation(self, request, response, spider):
        return response
